# services/inference_api.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import paddle
import numpy as np
from models.efficient_time_llm import EfficientTimeLLM
from predict_ensemble import sliding_window_predict

app = FastAPI()

# 加载多个模型用于集成
ensemble_models = [
    paddle.load('ensemble_models/model_0.pdparams'),
    paddle.load('ensemble_models/model_1.pdparams'),
    paddle.load('ensemble_models/model_2.pdparams')
]

class PredictionRequest(BaseModel):
    history: list
    time_features: list
    pred_steps: int = 24

@app.post("/predict")
def predict(req: PredictionRequest):
    if len(req.history) < 96:
        raise HTTPException(status_code=400, detail="历史数据长度必须 ≥ 96")

    history = np.array(req.history)
    time_features = np.array(req.time_features)

    # 滑动预测 + 集成
    preds = []
    for model_state in ensemble_models:
        model = EfficientTimeLLM(n_vars=history.shape[1])
        model.set_state_dict(model_state)
        pred = sliding_window_predict(model, history, time_features, req.pred_steps)
        preds.append(pred)

    final_pred = np.mean(preds, axis=0)
    return {"prediction": final_pred.tolist()}
